package com.zq.blog_serve.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zq.blog_serve.common.AjaxResult;
import com.zq.blog_serve.entity.LoginUser;
import com.zq.blog_serve.entity.SysUser;
import com.zq.blog_serve.entity.condition.BaseCondition;
import com.zq.blog_serve.service.system.SysUserService;
import com.zq.blog_serve.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Autowired
    SysUserService userService;

    @GetMapping("getInfo")
    public SysUser info(HttpServletRequest request) {
        // 获取SecurityContext对象
        LoginUser loginUser = SecurityUtils.getLoginUser();
        return loginUser.getSysUser();
    }

    @PostMapping("selectUserList")
    public AjaxResult selectUserList(@RequestBody BaseCondition condition) {
        Page page = new Page(condition.getCurrentPage(), condition.getPageSize());
        page = userService.page(page);
        return AjaxResult.success(page);
    }

    @PostMapping("insert")
    public AjaxResult insert(@RequestBody SysUser sysUser) {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        sysUser.setPwd(bCryptPasswordEncoder.encode("123456"));
        userService.save(sysUser);
        return AjaxResult.success();
    }

    @GetMapping("delete/{id}")
    public AjaxResult delete(@PathVariable("id") String id) {
        userService.removeById(id);
        return AjaxResult.success();
    }
}
